package com.ilop.sthome.ui.activity.detail.socket;

import android.content.Intent;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;

import com.ilop.sthome.ui.activity.main.ContainLoginActivity;
import com.example.common.utils.LiveDataBus;
import com.ilop.sthome.common.CommonId;
import com.ilop.sthome.common.command.SiterCommand;
import com.ilop.sthome.data.event.EventAnswerOK;
import com.ilop.sthome.data.greenDao.DeviceInfoBean;
import com.ilop.sthome.mvp.contract.device.SocketLinkageContract;
import com.ilop.sthome.mvp.present.device.SocketLinkagePresenter;
import com.ilop.sthome.ui.adapter.scene.TriggerInAdapter;
import com.ilop.sthome.ui.adapter.scene.TriggerOutAdapter;
import com.ilop.sthome.ui.dialog.TipDialog;
import com.siterwell.familywellplus.R;
import com.siterwell.familywellplus.databinding.ActivityLinkageDetailBinding;

import java.util.List;

/**
 * @author skygge
 * @date 2020-04-06.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：插座联动
 */
public class SocketLinkageActivity extends ContainLoginActivity<SocketLinkagePresenter, ActivityLinkageDetailBinding> implements SocketLinkageContract.IView {

    private String mRecommendId;
    private String mDeviceName;
    private int mDeviceId;
    private int mMid;
    private boolean isModify;
    private boolean hasModify;

    private TriggerInAdapter mInAdapter;
    private TriggerOutAdapter mOutAdapter;

    private List<DeviceInfoBean> inputList;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_linkage_detail;
    }

    @Override
    protected void initialize() {
        super.initialize();
        mRecommendId = getIntent().getStringExtra(CommonId.KEY_RECOMMEND_ID);
        mDeviceName = getIntent().getStringExtra(CommonId.KEY_DEVICE_NAME);
        mDeviceId = getIntent().getIntExtra(CommonId.KEY_DEVICE_ID, -1);
        mMid = getIntent().getIntExtra(CommonId.KEY_AUTOMATION, -1);
    }

    @Override
    protected void initPresent() {
        super.initPresent();
        mPresent = new SocketLinkagePresenter(mContext, mRecommendId);
    }

    @Override
    protected void initView() {
        super.initView();
        mInAdapter = new TriggerInAdapter(mContext);
        mOutAdapter = new TriggerOutAdapter(mContext);
        mDBind.linkageInList.setAdapter(mInAdapter);
        mDBind.linkageInList.setLayoutManager(new LinearLayoutManager(mContext));
        mDBind.linkageOutList.setLayoutManager(new LinearLayoutManager(mContext));
        mDBind.linkageOutList.setAdapter(mOutAdapter);
    }

    @Override
    protected void initData() {
        super.initData();
        isModify = mPresent.getAutomationInfo(mMid, mDeviceName);
        mPresent.getInputList();
        mPresent.getOutputList(mDeviceName, mDeviceId);
        if (isModify){
            mDBind.btDeleteLinkage.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void initListener() {
        super.initListener();
        mDBind.linkageInEmpty.setOnClickListener(view -> mPresent.addNewInput());
        mDBind.linkageInAdd.setOnClickListener(view -> mPresent.addNewInput());
        mDBind.tvSaveLinkage.setOnClickListener(view -> mPresent.onSendAutomation());
        mDBind.btDeleteLinkage.setOnClickListener(view -> {
            TipDialog dialog = new TipDialog(mContext, ()->{
                showProgressDialog();
                mPresent.onDeleteAutomation();
            });
            dialog.setMsg(getString(R.string.delete_automation));
            dialog.show();
        });
        mDBind.ivBack.setOnClickListener(view -> mPresent.whetherToSave(hasModify));
    }

    @Override
    protected void initDataBus() {
        super.initDataBus();
        LiveDataBus.get().with(CommonId.INPUT_CONDITION, DeviceInfoBean.class).observe(this, device -> {
            assert device != null;
            if (mPresent.checkInput(device)){
                inputList.add(device);
                mPresent.setInputList(inputList);
                hasModify = true;
            }
        });
        LiveDataBus.get().with(CommonId.INPUT_UPDATE, DeviceInfoBean.class).observe(this, device -> {
            mPresent.checkUpdateInput(device);
            hasModify = true;
        });
        LiveDataBus.get().with(CommonId.OUTPUT_UPDATE, DeviceInfoBean.class).observe(this, device -> {
            mPresent.checkUpdateOutput(device);
            hasModify = true;
        });
        LiveDataBus.get().with(CommonId.DELETE_CONDITION, Boolean.class).observe(this, isInput -> {
            mPresent.deleteAction(isInput);
            hasModify = true;
        });
        LiveDataBus.get().with(CommonId.INPUT_CLICK, Integer.class).observe(this, integer ->
                mPresent.updateAction(true, integer));

        LiveDataBus.get().with(CommonId.OUTPUT_CLICK, Integer.class).observe(this, integer ->
                mPresent.updateAction(false, integer));
        LiveDataBus.get().with(CommonId.KEY_ANSWER_OK, EventAnswerOK.class).observe(this, event -> {
            if (event!=null){
                Log.i(TAG, "initDataBus: answerOK");
                dismissProgressDialog();
                if (event.getData_str1().length() == 9) {
                    String code = event.getData_str2();
                    int cmd = Integer.parseInt(event.getData_str1().substring(0, 4), 16);
                    if (cmd == SiterCommand.INCREASE_AUTOMATION) {
                        if (CommonId.KEY_SUCCESS.equals(code.substring(0, 2))) {
                            mPresent.onSendSuccess(code.substring(3));
                        } else {
                            showToast(getString(R.string.failed));
                        }
                    } else if (cmd == SiterCommand.DELETE_AUTOMATION) {
                        if (CommonId.KEY_SUCCESS.equals(code.substring(0, 2))) {
                            showToast(getString(R.string.delete_success));
                            mPresent.onDeleteSuccess();
                        } else {
                            showToast(getString(R.string.failed));
                        }
                    }else if (cmd == SiterCommand.MODIFY_AUTOMATION) {
                        if (CommonId.KEY_SUCCESS.equals(code.substring(0, 2))) {
                            showToast(getString(R.string.modify_successfully));
                            mPresent.onSendSuccess(code.substring(3));
                        } else {
                            showToast(getString(R.string.failed));
                        }
                    }
                }
            }
        });
    }

    @Override
    public void showInputList(List<DeviceInfoBean> input) {
        inputList = input;
        if (input == null || input.size() == 0){
            mDBind.linkageInAdd.setVisibility(View.GONE);
            mDBind.linkageInEmpty.setVisibility(View.VISIBLE);
        }else {
            mDBind.linkageInAdd.setVisibility(View.VISIBLE);
            mDBind.linkageInEmpty.setVisibility(View.GONE);
        }
        mInAdapter.setList(input);
    }

    @Override
    public void showOutputList(List<DeviceInfoBean> output) {
        mOutAdapter.setList(output);
    }

    @Override
    public void startActivityByIntent(Intent intent) {
        startActivity(intent);
    }

    @Override
    public void showProgress() {
        showProgressDialog();
    }

    @Override
    public void showMsg(String msg) {
        showToast(msg);
    }

    @Override
    public void finishActivity() {
        dismissProgressDialog();
        finish();
    }

    @Override
    public void onBackPressed() {
        mPresent.whetherToSave(hasModify);
    }
}
